package com.th.coupon.service.impl;

import com.th.coupon.common.exception.BaseCloudException;
import com.th.coupon.common.vo.response.ExceptionResultData;
import com.th.coupon.dao.CouponTemplateDao;
import com.th.coupon.entity.CouponTemplate;
import com.th.coupon.service.IAsyncService;
import com.th.coupon.service.IBuildTemplateService;
import com.th.coupon.vo.TemplateRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 构建优惠卷模板服务实现
 * @author 涂航
 */
@Service
@Slf4j
public class IBuildTemplateServiceImpl implements IBuildTemplateService {

    /**
     * 异步服务
     */
    private final IAsyncService asyncService;
    /**
     * 模板优惠卷持久层
     */
    private final CouponTemplateDao couponTemplateDao;

    @Autowired
    public IBuildTemplateServiceImpl(IAsyncService asyncService, CouponTemplateDao couponTemplateDao) {
        this.asyncService = asyncService;
        this.couponTemplateDao = couponTemplateDao;
    }

    /**
     * 构建优惠卷模板
     * @param request {@link TemplateRequest} 模板信息请求对象
     * @return {@link CouponTemplate} 优惠卷模板实体
     * @throws BaseCloudException
     */
    @Override
    public CouponTemplate buildTemplate(TemplateRequest request) throws BaseCloudException {

        if(!request.validate()){
            //参数效验失败
            throw new BaseCloudException(ExceptionResultData.PARAMETER_VALIDITY_FAILED);
        }
        //模板名称不能同名
        if (null != couponTemplateDao.findByName(request.getName())){
            throw new BaseCloudException(ExceptionResultData.THE_TEMPLATE_NAME);
        }

        //构造CouponTemplate 并保存到数据库中
        CouponTemplate couponTemplate = requestToTemplate(request);
        couponTemplate = couponTemplateDao.save(couponTemplate);

        //根据优惠卷模板异步生成优惠卷码
        asyncService.asyncConstructCouponByTemplate(couponTemplate);

        return couponTemplate;
    }


    /**
     * 将TemplateRequest 转化成 CouponTemplate
     * @param request {@link TemplateRequest}
     * @return {@link CouponTemplate}
     */
    private CouponTemplate requestToTemplate(TemplateRequest request){
        return new CouponTemplate(
                request.getName(),
                request.getLogo(),
                request.getDesc(),
                request.getCategory(),
                request.getProductLine(),
                request.getCount(),
                request.getUserId(),
                request.getTarget(),
                request.getTemplateRule()
        );
    }
}
